package com.projectsexception.festivales.provider.handlers;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.projectsexception.festivales.provider.model.Info;
import com.projectsexception.festivales.provider.util.SAXHandlerUtil;

public class InfoHandler extends DefaultHandler {
    
    private static final String INFO_ELEMENT = "info";
    private static final String TYPE_ATTRIBUTE = "type";
    private static final String TITLE_ELEMENT = "title";
    private static final String DESC_ELEMENT = "description";
    
    private List<Info> infos;
    private transient Info tmpInfo;
    private transient StringBuilder sb;
    private transient boolean data;

    @Override
    public void startDocument() {
        infos = new ArrayList<Info>();
    }

    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        String s = SAXHandlerUtil.getElementName(localName, qName);
        if (s.equals(INFO_ELEMENT)) {
            tmpInfo = new Info();            
            tmpInfo.setType(attributes.getValue(TYPE_ATTRIBUTE));
        } else if ((s.equals(TITLE_ELEMENT)) || (s.equals(DESC_ELEMENT))) {
            sb = new StringBuilder();
            data = true;
        }
    }
    
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
        if (data) {
            sb.append(new String(ch, start, length));
        }
    }
    
    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException {
        String s = SAXHandlerUtil.getElementName(localName, qName);
        if (s.equals(TITLE_ELEMENT)) {
            data = false;
            tmpInfo.setTitle(SAXHandlerUtil.cleanString(sb.toString()));
        } else if (s.equals(DESC_ELEMENT)) {
            data = false;
            tmpInfo.setDescription(SAXHandlerUtil.cleanString(sb.toString()));
        } else if (s.equals(INFO_ELEMENT)) {
            infos.add(tmpInfo);
        }
    }

    public List<Info> getResult() {
        return infos;
    }

}
